package com.fr71.project.dm.utils;

import com.fr71.common.utils.spring.SpringUtils;
import com.fr71.project.dm.domain.PdUser;
import com.fr71.project.dm.service.IPdUserService;

import java.util.Date;
import java.util.List;
import java.util.TimerTask;

public class TaskFactroy {

    private static IPdUserService iPdUserService;

    private static IPdUserService getIPdUserService() {
        if (iPdUserService == null) {
            iPdUserService = SpringUtils.getBean(IPdUserService.class);
        }
        return iPdUserService;
    }

    /**
     * 重置每月换绑次数
     */
    public static TimerTask resetAllMonthChangeTimes() {
        return new TimerTask() {
            @Override
            public void run() {
                runTask(() -> {
                    getIPdUserService().resetAllMonthChangeTimes();
                    RedisUtil.clearTryCodeTimes();
                });
            }
        };
    }

    /**
     * 刷新用户表使用时长
     */
    public static void refreshUesedTime() {
        runTask(new Runnable() {
            @Override
            public void run() {
                List<PdUser> users = getIPdUserService().selectPdUserList(new PdUser() {{
                    setOnlines("Y");
                }});
                for (PdUser it : users) {
                    it.setTotalUsedTime(it.getTotalUsedTime() + new Date().getTime() - it.getLastConnectTime().getTime());
                    getIPdUserService().updatePdUser(it);
                }
            }
        });
    }

    private static void runTask(Runnable task) {
        task.run();
    }
}